package com.jihox.abookpro.domain;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Vector;

import com.thoughtworks.xstream.XStream;

public class BookProject  extends BookProjectSummary implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Book book;
	private Vector<File> images = new Vector<File>();
	private String xmlns = "http://www.example.org/PhotoBook";

	public BookProject() {
		super();
	}

	public Book getBook() {
		return book;
	}

	public void setBook(Book book) {
		this.book = book;
	}

	public Vector<File> getImages() {
		return images;
	}

	public void setImages(Vector<File> images) {
		this.images = images;
	}
	
	public String toString(){
		String result = "";

//		XStream xstream = new XStream(new DomDriver()) {
//			@Override
//			protected MapperWrapper wrapMapper(MapperWrapper next) {
//				return new MyMapperWrapper(next);
//			}
//		};
		XStream xstream = new XStream();
		xstream.alias("bookProject", BookProject.class);
		xstream.useAttributeFor(BookProject.class, "xmlns");
		xstream.alias("bookTemplate", BookTemplate.class);
		xstream.alias("page", Page.class);
		xstream.alias("pagePicture", PagePicture.class);
		xstream.alias("caption", Caption.class);
		xstream.alias("color", Color.class);
		xstream.addImplicitCollection(Book.class, "pages");
		xstream.addImplicitCollection(Page.class, "pictures",PagePicture.class);
		xstream.addImplicitCollection(Page.class, "captions",Caption.class);

		result = xstream.toXML(this);
		
		return result;
	}
	
	public static BookProject parse(String str){
		BookProject project = null;
		if (str == null || str.isEmpty()) {
			return project;
		}

		try {

			XStream xStream = new XStream();
			xStream.alias("bookProject", BookProject.class);
			xStream.alias("book", Book.class);
			xStream.alias("bookTemplate", BookTemplate.class);
			xStream.alias("page", Page.class);
			xStream.alias("pagePicture", PagePicture.class);
			xStream.alias("caption", Caption.class);
			xStream.alias("color", Color.class);
			xStream.addImplicitCollection(Book.class, "pages");
			xStream.addImplicitCollection(Page.class, "pictures",PagePicture.class);
			xStream.addImplicitCollection(Page.class, "captions",Caption.class);
			project = new BookProject();
			project = (BookProject) xStream.fromXML(str);

		} catch (Exception ex) {
			ex.printStackTrace();
		} 
		return project;
	}
	
	public Object deepCopy() throws Exception {
		// 将该对象序列化成流,因为写在流里的是对象的一个拷贝，而原对象仍然存在于JVM里面。所以利用这个特性可以实现对象的深拷贝
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		ObjectOutputStream oos = new ObjectOutputStream(bos);
		oos.writeObject(this);
		// 将流序列化成对象
		ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
		ObjectInputStream ois = new ObjectInputStream(bis);
		return ois.readObject();
	}

}
